<?php
namespace gnomephp\mvc;

class State{
	
	const STATE_SESSION_NAME = 'gnomephp.state.previous';
	
	/**
	 * Session storage.
	 * @var gnomephp\Session
	 */
	protected $session;
	
	
	public function __construct($session){
		$this->session = $session;
	}
	
	/**
	 * Saves the request state and on next request getSavedState() will return the StateItem object, wich is possible to execute.
	 * 
	 */
	public function save(){
		$item = new StateItem($_SERVER, (isset($_POST) && count($_POST) > 0 ? $_POST : null));
		
		$this->session->set(State::STATE_SESSION_NAME, $item);
		$this->session->save();
	}
	
	/**
	 * Returns the previous state if any.
	 * You can execute() on the StateItem wich will return the contents of the previous request.
	 * This is useful if you want a login page to get the contents of the previous requested page.
	 * @return gnomephp\mvc\StateItem Returns null if no previous state was saved.
	 */
	public function getSavedState(){
		if ($state = $this->session->get(State::STATE_SESSION_NAME)){
			return $state;
		}
		return null;
	}
	
	
	/**
	 * Deletes the previous state 
	 */
	public function deleteState(){
		if ($state = $this->session->get(State::STATE_SESSION_NAME)){
			$this->session->delete(State::STATE_SESSION_NAME);
			$this->session->save();
		}
	}
	
}